import React, { useEffect, useRef, useState } from 'react';
import SplashScreen from 'react-native-splash-screen';
import * as common from '../utils/CommonUtils';

import {
  View,
  StyleSheet,
  ImageBackground,
  TouchableOpacity,
  Text,
  Platform,
  Alert,
  ActivityIndicator,
  FlatList,
  Image,
  RefreshControl,
  ScrollView,
  Linking,
  Dimensions,
  DeviceEventEmitter
} from 'react-native';
import { check, PERMISSIONS, RESULTS, request } from 'react-native-permissions';
import { BlurView } from "@react-native-community/blur";
import LinearGradient from 'react-native-linear-gradient';
import { ItemHRow, InputModal, NewAppModal,LoadModal } from '../compoment';

import BleManager, {
  BleManagerDidUpdateStateEvent,
  Peripheral,
} from 'react-native-ble-manager';
// import BleModule from '../utils/BleModule';
// import BleProtocol from '../utils/BleProtocol';
// import Characteristic from '../utils/components/Characteristic';
import { BleEventType, BleState } from '../utils/type';
import { Buffer } from 'buffer';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { connectDev, disConnectDev, updateAllData } from '../store/device/actions';
import { useDidMount, useWillUnmount, useIntervalWhen } from 'rooks';
import Spinner from 'react-native-loading-spinner-overlay';
import RBSheet from 'react-native-raw-bottom-sheet';
import * as Storage from '../utils/Storage';
import { bleModule, bleProtocol } from './bleConst';
import { ErrorArr } from '../utils/type'
import { showMessage } from 'react-native-flash-message';
import VersionNumber from 'react-native-version-number';
import { imageMap,nameMap,resetMap } from '../utils/devicesType';

// 注意: 需要确保全局只有一个实例，因为BleModule类保存着蓝牙的连接信息
// const bleModule = new BleModule();
// const bleProtocol = new BleProtocol();

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

function HomePage({ navigation, connectDev, disConnectDev, devName,
  deviceId, allData, kmStr, hadUpdate, updateAllData }) {
  // 正在扫描中
  const [scaning, setScaning] = React.useState(false);
  // 当前正在连接的蓝牙id
  const [connectingId, setConnectingId] = useState('');
  const [showSpinner, setShowSpinner] = useState(false);// 页面loading
  const [loadingText, setLoadingText] = useState('Loading data ...');// 页面loading文案
  const [imageType, setImageType] = useState(2);
  // 扫描的蓝牙列表
  const deviceMap = useRef(new Map<string, Peripheral>());
  const [data, setData] = useState<Peripheral[]>([]);
  const [showList, setShowList] = useState(false); // 蓝牙列表弹窗

  const [resetModel, setResetModel] = useState(false); // 重置弹窗
  const [updateModel, setUpdateModel] = useState(false); // 更新弹窗
  const [xlrefreshing, setXlrefreshing] = React.useState(false);// 蓝牙列表搜索中
  // 电压电流等动态数据
  const [dyItem, setDyItem] = useState([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);

  // 适配新车型
  let tmpItem: Array<number> = [];

  let setArrData = [
    {
      id: 's1',
      sv: allData[0] ? allData[0][32] == 1 : false,
      unit: '',
      des: 'Enable/Disable Kickstand Sensor',
      type: 0,
    },
    {
      id: 's2',
      sv: allData[0] ? allData[0][20] == 1 : false,
      unit: '',
      des: 'Enable/Disable Brake Sensor',
      type: 0,
    },
    {
      id: 's4',
      sv: '',
      unit: '',
      des: 'Restore Factory Settings',
      type: 4,
    }];

      // componentDidMount
  React.useEffect(() => {
    setTimeout(() => {
      SplashScreen.hide();
      checkUpdate();
    }, 3000);
  }, []);

  async function checkUpdate() {

    return fetch(Platform.OS === 'ios' ? 'https://mock.apipark.cn/m1/3367046-647647-default/appUpdate' : 'https://apifoxmock.com/m1/3367046-647647-default/appUpdate2')
      .then((response) => response.json())
      .then((responseJson) => {

        let version1 = VersionNumber.appVersion;
        // console.log('当前 version:', responseJson)
        // console.log('应用市场 version:', responseJson.newVersion)
        let version2 = responseJson.newVersion;

        if (isUpdate(version1, version2)) {
          // 应用市场存在  且 当前版本 小于应用市场版本  跳转应用市场
          // 弹出更新弹窗，确定后跳转
          setUpdateModel(true);
        }
      }).catch((error) => {
        console.error(error);
      });
  }

  function isUpdate(version1, version2) {
    let arr1 = version1.split('.');
    let arr2 = version2.split('.');
    for (let i = 0; i < arr1.length;) {
      if (arr1[i] == arr2[i]) {
        i++
      } else {
        if (arr1[i] < arr2[i]) {
          return true;
        } else {
          return false;
        }
      }
    }
    return false;
  }

  // 电压电流 故障
  useIntervalWhen(
    () => {
      // 读故障
      bleModule['write']('010302580018c5ab', 0).then(() => { }).catch(err => {
        alert('Disconnected');
      })
    },
    1500,
    deviceId && !showSpinner && !hadUpdate,
    false,
  );

  useEffect(() => {
    bleModule.start();
  }, []);

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerLeft: () => deviceId ? (
        <TouchableOpacity
          onPress={async () => {
            bleModule.disconnect();
          }} style={{ paddingHorizontal: 15 }}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Image
              source={require('../images/left_blue.png')}
              style={{ height: 24, width: 24 }}
            />
            { allData[0] ? <Text>Model Number：{allData[0][24]}</Text> : null }
          </View>
        </TouchableOpacity>
      ) : null,
      headerRight: () => deviceId ? (
        <TouchableOpacity
          onPress={async () => {
            // console.log('循环写入/n');
          }}
          style={{ paddingHorizontal: 15 }}>
          {
            deviceId ? <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Text>{devName}</Text>
              {/* <Image
                source={require('../images/right_edit.png')}
                style={{ height: 24, width: 24 }}
              /> */}
            </View> : null
          }

        </TouchableOpacity>
      ) : null,
    });
  }, [navigation, deviceId,allData]);

  const crc16 = (data) => {
    let crcValue = 0xFFFF;
    for (let i = 0; i < data.length; i++) {
      crcValue ^= data[i] & 0xFFFF
      for (let j = 0; j < 8; j++) {
        if (crcValue & 0x0001) {
          crcValue >>= 1
          crcValue ^= 0xA001
        } else {
          crcValue >>= 1
        }
      }
    }

    crcValue = (Array(4).join('0') + crcValue.toString(16)).slice(-4);
    let crcArr = new Array(2)
    crcArr[0] = crcValue.substring(2, 4)
    crcArr[1] = crcValue.substring(0, 2)
    return crcArr;
  }

  const startScan = () => {
    if (Platform.OS === 'ios') {
      scan();
    } else {
      checkLocation();
    }
  };

  const checkLocation = () => {
    // 安卓要请求定位
    check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION)
      .then(result => {
        switch (result) {
          case RESULTS.UNAVAILABLE:
            console.log(
              'This feature is not available (on this device / in this context)',
            );
            break;
          case RESULTS.DENIED:
            console.log(
              'The permission has not been requested / is denied but requestable',
            );
            request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION).then(result => {
              // console.log('request result:' + result);
              // 本次 granted  使用时 granted  拒绝denied
              if (result === RESULTS.GRANTED) {
                checkLocation();
              }
            });
            break;
          case RESULTS.LIMITED:
            console.log('The permission is limited: some actions are possible');
            break;
          case RESULTS.GRANTED:
            scan();
            break;
          case RESULTS.BLOCKED:
            console.log('The permission is denied and not requestable anymore');
            break;
        }
      })
      .catch(error => {
        // …
      });
  };

  const alert = (text) => {
    Alert.alert('', text, [{ text: 'Ok', onPress: () => { } }]);
  }

  function sleep(ms: number) {
    return new Promise<void>(resolve => setTimeout(resolve, ms));
  }

  const onRefresh = React.useCallback(() => {
    setXlrefreshing(false);
    startScan();
    // wait(1000).then(() => setXlrefreshing(false));
  }, []);

  useEffect(() => {
    const updateStateListener = bleModule.addListener(
      BleEventType.BleManagerDidUpdateState,
      handleUpdateState,
    );
    const stopScanListener = bleModule.addListener(
      BleEventType.BleManagerStopScan,
      handleStopScan,
    );
    const discoverPeripheralListener = bleModule.addListener(
      BleEventType.BleManagerDiscoverPeripheral,
      handleDiscoverPeripheral,
    );
    const connectPeripheralListener = bleModule.addListener(
      BleEventType.BleManagerConnectPeripheral,
      handleConnectPeripheral,
    );
    const disconnectPeripheralListener = bleModule.addListener(
      BleEventType.BleManagerDisconnectPeripheral,
      handleDisconnectPeripheral,
    );
    const updateValueListener = bleModule.addListener(
      BleEventType.BleManagerDidUpdateValueForCharacteristic,
      handleUpdateValue,
    );

    return () => {
      updateStateListener.remove();
      stopScanListener.remove();
      discoverPeripheralListener.remove();
      connectPeripheralListener.remove();
      disconnectPeripheralListener.remove();
      updateValueListener.remove();
    };
  }, []);

  /** 蓝牙状态改变 */
  function handleUpdateState(event: BleManagerDidUpdateStateEvent) {
    console.log('BleManagerDidUpdateState:', event);
    bleModule.bleState = event.state;
    // 蓝牙打开时自动扫描
    if (event.state === BleState.Off) {
      disConnectDev();
      allData = [];
      updateAllData([]);
    }
  }

  /** 扫描结束监听 */
  function handleStopScan() {
    console.log('Scanning is stopped');
    setScaning(false);
  }

  /** 搜索到一个新设备监听 */
  function handleDiscoverPeripheral(data: Peripheral) {
    // console.log('BleManagerDiscoverPeripheral:', data);
    // 蓝牙连接 id
    let id;
    // 蓝牙 Mac 地址
    let macAddress;
    if (Platform.OS == 'android') {
      macAddress = data.id;
      id = macAddress;
    } else {
      // ios连接时不需要用到Mac地址，但跨平台识别同一设备时需要 Mac 地址
      macAddress = bleProtocol.getMacFromAdvertising(data);
      id = data.id;
    }
    deviceMap.current.set(data.id, data);
    setData([...deviceMap.current.values()]);
  }

  
  function loopWithTimeout(index, length, interval, callback) {
    if (index < length) {
        callback(index); // 执行当前循环的操作
        setTimeout(function() {
            loopWithTimeout(index + 1, length, interval, callback); // 递归调用
        }, interval);
    }
  }

  /** 蓝牙设备已连接 */
  async function handleConnectPeripheral(data: Peripheral) {
    console.log('BleManagerConnectPeripheral:', data);
    // 连接后从硬件读取所需数据
    setShowSpinner(true);

    // 等待8s
    loopWithTimeout(1, 9, 1000, function(index) {
      console.log('Iteration:', index);
      setLoadingText('Loading data...'+(index*8)+'%');
      // 在这里执行每次循环需要进行的操作
    });
    
    await sleep(8000);
    // 避免未拿到数据 弹窗不消失
    setTimeout(function () {
      setShowSpinner(false);
    }, 4000);
    
    console.log('读取分片10-19数据/n');
    let tmpAA = [
      '01030000001845c0', '010300d80018c5fb', '010300f0001845f3',
      '010301080018c5fe', '01030120001845f6', '010301380018c5f1',
      '010301500018442d', '010301680018c5e0', '01030180001845d4'
    ];
    for (var i = 0; i < 9; i++) {
      (function (t) {
        setTimeout(function () {
          bleModule['write'](tmpAA[t], 0).then(() => { }).catch(err => {
            alert('Sending failed');
          })
        }, 300 * (t + 3));
      })(i)
    }
  }

  // for (var i = 9; i < 19; i++) {
  //   (function (t) {   // 注意这里是形参
  //     let tmpStr = (Array(4).join(0) + (t * 24).toString(16)).slice(-4);
  //     var res = crc16(Buffer.from('0103' + tmpStr + '0018', "hex"));
  //     setTimeout(function () {
  //       bleModule['write']('0103' + tmpStr + '0018' + res[0] + res[1], 0).then(() => { }).catch(err => {
  //         alert('Sending failed');
  //       })
  //     }, 200 * t);
  //   })(i)
  // }
  // }

  /** 蓝牙设备已断开连接 */
  function handleDisconnectPeripheral(data: Peripheral) {
    console.log('BleManagerDisconnectPeripheral:', data);
    // initData();
    disConnectDev();
    allData = [];
    tmpItem = [];
    updateAllData([]);
  }

  /** 接收到新数据 */
  async function handleUpdateValue(data: any) {
    let value: Array<number> = data.value;
    if (value.length == 8) {
      console.log('recive:', value);
      return;
    }

    // 1.0版本
    // if (allData.length < 9 && value.length == 53) {
    //   allData.push(value);
    //   if (allData.length == 9) {
    //     updateAllData([...allData]);
    //     console.log('allData:', allData);
    //     // allData[9] ? allData[9][4] == 1 : false
    //     if(allData[0][24] < 7 && allData[0][24] > 1) {
    //       changeType(allData[0][24]);
    //       setImageType(allData[0][24]);
    //     }
    //     setShowSpinner(false);
    //   }
    // } else {
    //   console.log('BluetoothUpdateValue:', value);
    //   // 这里是非总数据的数据
    //   if (value.length == 53) {
    //     setDyItem(value);
    //   }
    // }


    // 兼容新车型版本
    if (value.length != 13 && value.length != 20 && value.length != 53) {
      console.log('no use recive:', value);
      return;
    } else {
      tmpItem.push(...value);
      if (tmpItem.length != 53) {
        return;
      }
    }
    if (allData.length < 9) {
      allData.push(tmpItem);
      setLoadingText('Loading data...'+(allData.length*4+64)+'%');
      if (allData.length == 9) {
        updateAllData([...allData]);
        if(allData[0][24] < 7 && allData[0][24] >= 0) {
          setImageType(allData[0][24]);
        } else {
          // 非法车型，断开连接，弹窗提示：车型编码不支持，请联系售后。
          onNotSupport();
        }
        await sleep(400);
        setShowSpinner(false);
        setLoadingText('');
        DeviceEventEmitter.emit('readSuccess');
      }
    } else {
      // console.log('BluetoothUpdateValue:', value);
      // 这里是非总数据的数据
        setDyItem(tmpItem);
    }
    tmpItem = [];
  }

  function enableBluetooth() {
    if (Platform.OS === 'ios') {
      alert('Please turn on Bluetooth.');
    } else {
      Alert.alert('Tip', 'Please turn on Bluetooth.', [
        {
          text: 'Cancel',
          onPress: () => { },
        },
        {
          text: 'Open',
          onPress: () => {
            bleModule.enableBluetooth();
          },
        },
      ]);
    }
  }

  function notify(index: number) {
    bleModule
      .startNotification(index)
      .then(() => {
        // setIsMonitoring(true);
        // alert('开启成功');
      })
      .catch(err => {
        // setIsMonitoring(false);
        // alert('开启失败');
      });
  }

  /** 连接蓝牙 */
  function connect(item: Peripheral) {
    setConnectingId(item.id);
    setScaning(false);
    if (scaning) {
      // 当前正在扫描中，连接时关闭扫描
      bleModule.stopScan().then(() => {
        setScaning(false);
      });
      bleModule.stopScan();
      setScaning(false);
    }

    bleModule
      .connect(item.id)
      .then(peripheralInfo => {
        setShowList(false);

        connectDev({ name: peripheralInfo.name, uid: peripheralInfo.id });
        // notify(0);
        // notify(1);
        bleModule.startSNotification();
        // 连接成功后，列表只显示已连接的设备
        // setData([item]);
      })
      .catch(err => {
        alert('连接失败');
      })
      .finally(() => {
        setConnectingId('');
      });
    // });
  }

  const scan = () => {

    if (bleModule.bleState !== BleState.On) {
      enableBluetooth();
      return;
    }

    if (!scaning) {
      setShowList(true);
      setScaning(true);
      // 重新扫描时清空列表
      deviceMap.current.clear();
      bleModule
        .scan()
        .then(() => {
          setScaning(true);
        })
        .catch(err => {
          if (err.errorCode == 601) {
            alert(
              'Please turn on the mobile phone to locate and search again.',
            );
          }
          if (err.errorCode == 102) {
            alert('Please turn on Bluetooth and search again.');
          }
          setScaning(false);
        });
    }
  };

  function renderItem(item: ListRenderItemInfo<Peripheral>) {
    const data = item.item;
    // const disabled = !!connectingId && connectingId !== data.id;
    return (
      <TouchableOpacity
        // disabled={disabled || isConnected}
        onPress={() => {
          console.log('item onPress')
          connect(data);
        }}>
        <View style={{
          height: 60,
          marginHorizontal: 50, alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row'
        }}>
          <Text style={styles.textItemName}>{data.name ? data.name : 'No name'}</Text>
          {
            connectingId === data.id ?
              <ActivityIndicator color="#414141" /> : <View />
          }
        </View>
        {/* <Text>{data.id}</Text> */}
        <View style={{ marginHorizontal: 50, height: 0, borderTopWidth: 1, borderColor: '#BDBDBD', margin: StyleSheet.hairlineWidth }} />
      </TouchableOpacity>
    );
  }

  const renderSetItem = ({ item, index }) => (
    <ItemHRow
      key={item.id}
      data={item}
      clickAction={() => clickAtIndex(index)}
    />
  );

  async function clickAtIndex(index) {
    let tmpStr = '';
    let tmpData = '';
    switch (index) {
      case 0:
        if (allData.length != 9) {
          alert('Data not obtained, please disconnect and reconnect the implementation.');
          return;
        }
        tmpStr = (Array(4).join(0) + (0).toString(16)).slice(-4);
        tmpData = '';
        if (allData[0][32] == 1) {
          allData[0][32] = 0;

          for (let j = 0; j < 48; j++) {
            const element = allData[0][3 + j];
            tmpData += (Array(2).join(0) + element.toString(16)).slice(-2);
          }
          var res = crc16(Buffer.from('0110' + tmpStr + '001830' + tmpData, "hex"));
          bleModule['write']('0110' + tmpStr + '001830' + tmpData + res[0] + res[1], 0).then(() => {
            updateAllData([...allData]);
            // setIsTest(!isTest);
          }).catch(err => {
            alert('Sending failed');
          });
        } else {
          allData[0][32] = 1;
          for (let j = 0; j < 48; j++) {
            const element = allData[0][3 + j];
            tmpData += (Array(2).join(0) + element.toString(16)).slice(-2);
          }
          var res = crc16(Buffer.from('0110' + tmpStr + '001830' + tmpData, "hex"));
          bleModule['write']('0110' + tmpStr + '001830' + tmpData + res[0] + res[1], 0).then(() => {
            updateAllData([...allData]);
            // setIsTest(!isTest);
          }).catch(err => {
            alert('Sending failed');
          });
        }

        await sleep(200);
        bleModule['write']('0110021E000200000000009B8F', 0).then(() => {
          console.log('send save order');
        }).catch(err => {
          alert('Sending failed');
        });
        
        break;
      case 1:
        if (allData.length != 9) {
          alert('Data not obtained, please disconnect and reconnect the implementation.');
          return;
        }
        tmpStr = (Array(4).join(0) + (0).toString(16)).slice(-4);
        tmpData = '';

        if (allData[0][20] == 1) {
          allData[0][20] = 0;
          for (let j = 0; j < 48; j++) {
            const element = allData[0][3 + j];
            tmpData += (Array(2).join(0) + element.toString(16)).slice(-2);
          }
          var res = crc16(Buffer.from('0110' + tmpStr + '001830' + tmpData, "hex"));
          bleModule['write']('0110' + tmpStr + '001830' + tmpData + res[0] + res[1], 0).then(() => {
            updateAllData([...allData]);
            // setIsTest(!isTest);
          }).catch(err => {
            alert('Sending failed');
          });
        } else {
          allData[0][20] = 1;
          for (let j = 0; j < 48; j++) {
            const element = allData[0][3 + j];
            tmpData += (Array(2).join(0) + element.toString(16)).slice(-2);
          }
          var res = crc16(Buffer.from('0110' + tmpStr + '001830' + tmpData, "hex"));
          bleModule['write']('0110' + tmpStr + '001830' + tmpData + res[0] + res[1], 0).then(() => {
            updateAllData([...allData]);
            // setIsTest(!isTest);
          }).catch(err => {
            alert('Sending failed');
          });
        }

        await sleep(200);
        bleModule['write']('0110021E000200000000009B8F', 0).then(() => {
          console.log('send save order');
        }).catch(err => {
          alert('Sending failed');
        });
        
        break;
        // case 2:
        //   // 切换公制和英制
        //   kmRBSheet.open();
        break;
      case 2:
        // onReTip();
        setResetModel(true);
        break;
      default:
        break;
    }
  }

  const onNotSupport = () => {
    Alert.alert('','This model is not supported, please contact after-sales customer service.', [{ text: 'Ok', onPress: () => {
      bleModule.disconnect();
    }}]);
}

  async function reSetFunction(index) {
    setShowSpinner(true);
    setLoadingText('Restrore Factory Settings...0%');
    let tmpdata = allData[0] ? resetMap[allData[0][24]] : resetMap[0];
    for (let i = 0; i < tmpdata.length; i++) {
      setLoadingText('Restrore Factory Settings...'+Math.round(i*4.545)+'%');
      await sleep(1100);
      let tmpData = '';
      for (let j = 0; j < tmpdata[i].length; j++) {
        const element = tmpdata[i][j];
        tmpData += (Array(2).join(0) + element.toString(16)).slice(-2);
      }
      bleModule['write'](tmpData, 0).then(() => { }).catch(err => {
        alert('Sending failed');
        return;
      })
      console.log('i:'+tmpData);
    }

    await sleep(400);
    bleModule['write']('0110021E000200000000009B8F', 0).then(() => {
      console.log('send save order');
    }).catch(err => {
      alert('Sending failed');
    });
    setLoadingText('Restrore Factory Settings...100%');
    await sleep(400);

    bleModule.disconnect();
    setShowSpinner(false);
    setLoadingText('');
    showMessage({
      message: 'Factory settings restored. Please reconnect.',
      type: 'info',
      icon: 'info',
      duration: 2000,
    });
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#DDDDDD' }}>
      <Spinner
        visible={showSpinner}
        textContent={loadingText}
        textStyle={{ color: '#FFF' }}
      />
      {
        deviceId ? <ImageBackground
          source={imageMap[imageType]}
          resizeMode='contain'
          style={styles.imageYes} >

          <ScrollView style={{ flex: 1, marginTop: '30%' }} showsVerticalScrollIndicator={false}>
            <View style={{ flex: 1, height: 100 }}></View>

            {/* 电压电流 */}
            <LinearGradient colors={['#DDDDDD00', '#DDDDDD']}>
              <View style={{ flex: 1, height: 110, flexDirection: 'row', alignItems: 'center', marginHorizontal: 20 }}>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.text, { textAlign: 'center', fontSize: 36 }]}>{dyItem ? ((dyItem[35] * 256 + dyItem[36] + dyItem[38] * 256 * 256) / 65536).toFixed(1) : 0}V</Text>
                  <View style={{ height: 35, backgroundColor: '#CFFF36', justifyContent: 'center' }}>
                    <Text style={[styles.text, { textAlign: 'center', fontSize: 14 }]}>Voltage</Text>
                  </View>
                </View>
                <View style={{ height: 90, width: StyleSheet.hairlineWidth, backgroundColor: '#BDBDBD', marginHorizontal: 30 }} />
                <View style={{ flex: 1 }}>
                  <Text style={[styles.text, { textAlign: 'center', fontSize: 36 }]}>{dyItem[41] > 128 ? (65536 - (dyItem[39] * 256 + dyItem[40] + dyItem[41] * 256 * 256 * 256 + dyItem[42] * 256 * 256) / 65536).toFixed(1) : ((dyItem[39] * 256 + dyItem[40] + dyItem[42] * 256 * 256) / 65536).toFixed(1)}A</Text>
                  <View style={{ height: 35, backgroundColor: '#CFFF36', justifyContent: 'center' }}>
                    <Text style={[styles.text, { textAlign: 'center', fontSize: 14 }]}>Current</Text>
                  </View>
                </View>
              </View>
            </LinearGradient>

            <View style={{ backgroundColor: '#DDDDDD' }}>
              <View style={{ marginHorizontal: 20, height: StyleSheet.hairlineWidth, backgroundColor: '#BDBDBD' }} />
            </View>
            {
              setArrData.map((item, index) => {
                return (renderSetItem({ item, index }))

              })
            }
            <Text style={{margin:20,fontSize:16,color:'red',fontFamily: 'Moldiv'}}>
            Please be aware that installing an incorrect controller version can damage the controller and render the bike non-operational. Refer to the following guidelines:{'\n\n'}
            <Text style={{color:'gray',fontSize:14}}>
            1.	ABC-: Contact us before updating the controller.{'\n'}
            2.	ABC+: Contact us before updating the controller.{'\n'}
            3.	ABZ: Contact us before updating the controller.{'\n'}
            4.	Mantis X: Use only for Mantis X models.{'\n'}
            5.	Mantis Mini: Use only for Mantis Mini models.{'\n'}
            </Text>
            </Text>
          </ScrollView>

        </ImageBackground> :
          <ImageBackground
            source={require('../images/bgimg_no.png')}
            // resizeMode='contain'
            style={styles.image} >
            {showList ? <BlurView style={styles.blur}
              blurType="light"
              blurAmount={16}
              reducedTransparencyFallbackColor="white">
              <FlatList
                style={{ width: '100%' }}
                renderItem={renderItem}
                ListHeaderComponent={
                  <View style={{ width: '100%', height: 80, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                    <Text style={styles.textList}>{scaning ? 'Searching... ' : 'Search complete'}</Text>
                    {scaning ? <ActivityIndicator color="#414141" size={'small'} /> : null}

                    <TouchableOpacity
                      style={{ position: 'absolute', top: 10, right: 10, width: 30, height: 30, alignItems: 'center', justifyContent: 'center' }}
                      onPress={() => { setShowList(false) }}
                    >
                      <Image onPress={() => { setShowList(false) }} source={require('../images/icon_cancle.png')} />
                    </TouchableOpacity>

                  </View>
                }
                keyExtractor={item => item.id}
                data={data}
                extraData={connectingId}
                refreshControl={
                  <RefreshControl refreshing={xlrefreshing} onRefresh={onRefresh} />}
              />
            </BlurView> : <TouchableOpacity style={styles.button} onPress={() => {
              // setConnectStatus(2); 
              // navigation.navigate('Bluetest');
              startScan();
              // 检查权限 全部ok  开始扫描 弹出列表
            }}>
              <Text style={styles.text}>Bluetooth Connect</Text>
            </TouchableOpacity>}
          </ImageBackground>
      }
      <InputModal
        isVisible={resetModel}
        modelName={allData[0] ? nameMap[allData[0][24]] : nameMap[0]}
        onCancle={() => {
          setResetModel(false);
        }}
        onSave={(index) => {
          setResetModel(false);
          setTimeout(() => {
            reSetFunction(index);
          }, 600);
        }}
      />
      <NewAppModal
        isVisible={updateModel}
        onCancle={() => {
          setUpdateModel(false);
        }}
        onSave={() => {
          setUpdateModel(false);
          if (Platform.OS === 'ios') {
            Linking.openURL('https://apps.apple.com/cn/app/daymak-drive-2/id6473576810').catch(err => console.error('An error occurred', err));
          } else {
            Linking.openURL(`https://play.google.com/store/apps/details?id=com.rawrrdriver`).catch(err => console.error('An error occurred', err));
          }

        }}
      />
          {/* {showSpinner ? <View style={{zIndex: 1000000,position:'absolute',width:windowWidth,height:windowHeight,justifyContent:'center',alignItems:'center',backgroundColor:'rgba(0, 0, 0, 0.25)'}}>
            <ActivityIndicator color="#FFF" size={'large'} />
            <Text style={{color:'#FFF'}}>Loading...</Text>
          </View> : null} */}

      {/* <LoadModal
        isVisible={showSpinner}
      /> */}
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: "column-reverse"
  },
  imageYes: {
    flex: 1,
    // width: '100%',
    marginTop: 20,
    height: '60%',

  },
  image: {
    flex: 1,
    marginTop: 20,
    // height: '90%',
    justifyContent: "flex-end"
  },
  button: {
    marginBottom: 40,
    marginHorizontal: 20,
    height: 60,
    backgroundColor: '#CFFF36',
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    color: "#060606",
    fontSize: 30,
    fontWeight: "500",
    fontFamily: 'Moldiv'
    // textAlign: "center",
  },
  textList: {
    color: "#060606",
    fontSize: 18,
    fontWeight: "400",
    fontFamily: 'Moldiv'
  },
  textItemName: {
    color: "#060606",
    fontSize: 16,
    fontWeight: "400",
    fontFamily: 'Moldiv'
  },
  item: {
    paddingHorizontal: 10,
    paddingVertical: 8,
  },
  blur: {
    marginBottom: 0,
    marginHorizontal: 0,
    height: '80%',
    backgroundColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center'
  },
  speedItem: {
    width: '100%',
    height: 56,
    // backgroundColor: '#282828',
    justifyContent: 'center',
    alignItems: 'center',
  },
  speedText: {
    color: '#fff',
    fontSize: 18,
  }
});

const mapStateToProps = ({
  device: {
    devName,
    deviceId,
    allData,
    kmStr,
    hadUpdate
  },
}) => ({
  devName,
  deviceId,
  allData,
  kmStr,
  hadUpdate
});

const enhance = compose(
  connect(mapStateToProps, {
    connectDev,
    disConnectDev,
    updateAllData
  }),
);
export default enhance(HomePage);

// let { width, height } = Dimensions.get('window')
// function dp(px: number) {
//     return Math.round(px * (width / 375))
// }

